<?php

class Service extends CActiveRecord
{
	/**
	 * The followings are the available columns in table '{{service}}':
	 * @var integer $id
	 * @var integer $user_id
	 * @var integer $type
	 * @var string $ip
	 * @var string $cost
	 * @var integer $packet_id
	 * @var integer $speed_id
	 * @var string $comment
	 * @var string $start_date
	 * @var string $end_date
	 * @var boolean $is_blocked
	 * @var string $pay_date
	 * @var string $last_pay_date
	 * @var boolean $is_active
	 * @var string $create_time
	 * @var string $update_time
	 */
	
	public $user_contract;	//Поле для поиска и сортировки по номеру договора
	public $user_username;
	
	private $_inC;
	private $_outC;
	private $_totalC;

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{service}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('user_id, type, cost', 'required'),
			array('user_id, type, packet_id, speed_id', 'numerical', 'integerOnly'=>true),
			array('cost', 'numerical'),
			array('ip', 'match', 'pattern'=>'/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/'),
			array('comment', 'length', 'max'=>128),
			array('start_date, end_date', 'type', 'type'=>'datetime', 'datetimeFormat'=>Yii::app()->locale->dateFormat),//.' '.Yii::app()->locale->timeFormat),
			array('is_blocked, is_active', 'boolean'),
			array('create_time, update_time, pay_date, last_pay_date', 'unsafe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, user_contract, user_username, user_id, type, ip, cost, packet_id, speed_id, comment, start_date, end_date, is_blocked, pay_date, last_pay_date, is_active, create_time, update_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'user'=>array(self::BELONGS_TO,'User','user_id',
					'select'=>'id,contract,username',),
			'speed'=>array(self::BELONGS_TO,'Speed','speed_id',
					'select'=>'id,name',),
			'packet'=>array(self::BELONGS_TO,'Packet','packet_id',
					'select'=>'id,name',),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => Yii::t('main','Id'),
			'user_contract' => Yii::t('main','Contract'),	//Поле для поиска и сортировки по номеру договора
			'user_username' => Yii::t('main','Username'),
			'user_id' => Yii::t('main','Username'),
			'type' => Yii::t('main','Type'),
			'ip' => Yii::t('main','Ip'),
			'cost' => Yii::t('main','Cost'),
			'packet_id' => Yii::t('main','Packet'),
			'speed_id' => Yii::t('main','Speed'),
			'comment' => Yii::t('main','Comment'),
			'start_date' => Yii::t('main','Start Date'),
			'end_date' => Yii::t('main','End Date'),
			'is_blocked' => Yii::t('main','Is Blocked'),
			'pay_date' => Yii::t('main','Pay Date'),			//FIXME нужно?
			'last_pay_date' => Yii::t('main','Last Pay Date'), //FIXME оно нужно?
			'is_active' => Yii::t('main','Is Active'),
			'create_time' => Yii::t('main','Create Time'),
			'update_time' => Yii::t('main','Update Time'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria(array('with'=>array('user','speed','packet')));

		$criteria->compare('t.id',$this->id);

		$criteria->compare('t.user_id',$this->user_id);
		
		$criteria->compare('user.username',$this->user_username,true);
		
		$criteria->compare('user.contract',$this->user_contract,true);

		$criteria->compare('t.type',$this->type);

		$criteria->compare('t.ip',$this->ip,true);

		$criteria->compare('t.cost',$this->cost,true);

		$criteria->compare('t.packet_id',$this->packet_id);

		$criteria->compare('t.speed_id',$this->speed_id);

		$criteria->compare('t.comment',$this->comment,true);

		$criteria->compare('t.start_date',$this->start_date,true);

		$criteria->compare('t.end_date',$this->end_date,true);

		$criteria->compare('t.is_blocked',$this->is_blocked);

		$criteria->compare('t.pay_date',$this->pay_date,true);

		$criteria->compare('t.last_pay_date',$this->last_pay_date,true);

		$criteria->compare('t.is_active',$this->is_active);

		$criteria->compare('t.create_time',$this->create_time,true);

		$criteria->compare('t.update_time',$this->update_time,true);

		return new CActiveDataProvider('Service', array(
			'criteria'=>$criteria,
			'pagination'=>array('pageSize'=>Setting::get('PerPage')),
			'sort'=>array(
				'defaultOrder'=>'user.contract',
				'attributes'=>array(
					'user_username'=>array(
						'asc'=>'user.username',
						'desc'=>'user.username DESC',
					),
					'user_contract'=>array(			//Поле для поиска и сортировки по номеру договора
						'asc'=>'user.contract',
						'desc'=>'user.contract DESC',
					),
					'type',
					'ip',
					'cost',
					'cost_this_month',
				),
			),
		));
	}
	
    public function getTotals()		//FIXME сделать статический масив типа
    {
    	$criteria=$this->search()->criteria;
    	$criteria->with='';
    	$criteria->select=new CDbExpression('SUM(cost) as cost, SUM(cost_this_month) as cost_this_month');
    	return $this->find($criteria);
    }
    
    public function activeServices($user_id, $date)
    {
    	if (!isset($user_id)) return 0;
		
		if (!isset($date)) $date = time();
    	
    	$criteria=new CDbCriteria;
		//$criteria->select='id,service_id,cost,comment,is_active';  // выбираем только нужные поля
		$criteria->condition='user_id=:userID AND is_active = 1 and start_date <= :date and (end_date is null or end_date="0000-00-00 00:00:00" or end_date >= :date)';
		$criteria->params=array(':userID'=>$user_id, ':date'=>date('Y-m-d H:i:s',$date));
		return $this->findAll($criteria);
    }
    
	public function getTotalCounters()
	{
		$sql='select sum(counter.world_in+counter.ukraine_in) as inp, sum(counter.world_out+counter.ukraine_out) as outp from {{counter}} as counter where counter.time between :begin and :end and counter.service_id=:service_id';
		$command = $this->dbConnection->createCommand($sql);
		$command->bindParam(':begin',date('Y-m-01'));
		$command->bindParam(':end',date('Y-m-d H:i:s'));
		$id=$this->id;
		$command->bindParam(':service_id',$id);
		$row=$command->queryRow();
        $this->_inC=sprintf('%.3f', $row['inp']/1048576);
        $this->_outC=sprintf('%.3f', $row['outp']/1048576);
        $this->_totalC=sprintf('%.3f', $this->_inC+$this->_outC);
	}
	
	public function getInC()
	{
		if (is_null($this->_inC)) $this->getTotalCounters();
		return $this->_inC;
	}
	
	public function getOutC()
	{
		if (is_null($this->_outC)) $this->getTotalCounters();
		return $this->_outC;
	}
	
	public function getTotalC()
	{
		if (is_null($this->_totalC)) $this->getTotalCounters();		
		return $this->_totalC;
	}
	
	public function behaviors()
    {
        return array(
			'History' => array(
                'class'=>'application.components.behaviors.HistoryBehavior',
            ),
            'DateTime' => array(
				'class'=>'application.components.behaviors.DateTimeBehavior',
			),
			'OldAttributes' => array(
				'class'=>'application.components.behaviors.OldAttributesBehavior',
			),
            'NotActiveOnDelete' => array(
            	'class'=>'application.components.behaviors.NotActiveOnDeleteBehavior',
            ),
        );
    }

}